const path = require('path');
const url = require('url');
module.exports = class extends think.Controller {
	constructor(ctx) {
		super(ctx);
		this.wxuser = this.model("weixin/user");
		this.conf = this.model("weixin/config");
		this.qrcode = this.model("taoke/qrcode");
		this.user = this.model("system/user");
		this.log = this.model("system/log");
		this.asset = this.model("system/asset");
		this.agency = this.model("system/agency");
		this.appid = think.config('setup.weixinAppid');

	}

	__before() {
		//if(!this.isWeixin()) {
		//	return this.fail("请用微信浏览器打开");
		//}

	}

	async indexAction() {
		try {

			const openid = await this.session('weixinOpenid');
			let user = await this.session('user');
			const weixin = await this.conf.where({
				appid: this.appid
			}).find();
			if(think.isEmpty(openid)) {

				const pingpp = require('pingpp')(weixin.appsecret);

				const oauthUrl = pingpp.wxPubOauth.createOauthUrlForCode(weixin.appid, `http://${this.ctx.host}/app/wxmp/oauth/getopenid`);

				return this.redirect(oauthUrl);
			}

			if(think.isEmpty(user)) {
				user = await this.wxuser.where({
					openid: openid
				}).find();
				let api = await this.wechatApi(weixin.id);
				let userInfo = await api.getUser(openid);
				userInfo.wxid = weixin.id;
				userInfo.nickname = think.emojiFilter(userInfo.nickname);
				if(think.isEmpty(user.nickname)) {

					await this.wxuser.where({
						openid: openid
					}).update(userInfo);

				}

				if(think.isEmpty(user.user_id)) {

					await this.wxuser.bindUser(user, userInfo);

					//return this.redirect('/app/wxmp/user/login');
				}

				user = await this.wxuser.where({
					openid: openid
				}).find();
				const filePath = path.join(think.ROOT_PATH, 'www/', '/upload/weixin/avatar/');
				think.mkdir(filePath);
				await this.spiderImage(userInfo.headimgurl, filePath + user.user_id + '.png');
				await this.session('user', user);

				return this.redirect(this.cookie('weixinUrl'));

			}
		} catch(e) {
			console.log(e)
		}

	}

	// 用微信客户端获取getopenid
	async getopenidAction() {
		try {
			const weixin = await this.conf.where({
				appid: this.appid
			}).find();

			const pingpp = require('pingpp')(weixin.appsecret);

			const code = this.get('code');
			console.log(code);

			const getopenid = () => {
				const deferred = think.defer();
				pingpp.wxPubOauth.getOpenid(weixin.appid, weixin.appsecret, code, function(err, openid) {

					deferred.resolve(openid);

				});
				return deferred.promise;
			};
			const openid = await getopenid();
			console.log(openid);
			console.log("11111111111111111111");
			const cookieUrl = this.cookie('weixinUrl');
			let api = await this.wechatApi(weixin.id);
			let userInfo = await api.getUser(openid);
	console.log(userInfo);
			if(userInfo.subscribe == 0) {

				let params = url.parse(cookieUrl, true).query;
				if(think.isInt(params.qrid)) {
					return this.redirect(`/app/wxmp/oauth/qrcode?id=${params.qrid}`);
				} else {
					return this.redirect(`/app/wxmp/oauth/qrcode?id=1`);
				}

			};

			let user = await this.wxuser.where({
				openid: openid
			}).find();

			await this.session('weixinOpenid', openid);

			if(think.isEmpty(user.user_id)) {

				userInfo.wxid = weixin.id;
				await this.wxuser.bindUser(user, userInfo);
			}
			user = await this.wxuser.where({
				openid: openid
			}).find();
			const filePath = path.join(think.ROOT_PATH, 'www/', '/upload/weixin/avatar/');
			think.mkdir(filePath);
			await this.spiderImage(userInfo.headimgurl, filePath + user.user_id + '.png');

			await this.session("user", user);
			return this.redirect(this.cookie('weixinUrl'));
		} catch(e) {
			console.log(e)
		}

	}
	async qrcodeAction() {
		let gets = this.get();
		let qrcode = await this.qrcode.where({
			id: gets.id
		}).find();
		this.assign("qrcode", qrcode.qrcode_url);

		return this.appDisplay();
	}

	async picAction() {
		let data = JSON.parse(this.get("data"));
		console.log(data.qrcode_url);
		this.assign("goods", data);
		return this.appDisplay();
	}
	
	async testAction(){
		let id = this.get("id");
		let alimama = think.service("alimama");
		let data = await alimama.transferLinkByTaobaoApi(id);
		return this.json(data);
	}
};